var map;
var fzLayer;//福州天地图
var mqLayer;//闽清天地图
var extentLayer;//查询范围图层
require(["dojo/dom","dojo/dom-construct","esri/map","esri/dijit/Scalebar","esri/tasks/Geoprocessor","esri/InfoTemplate","esri/tasks/FindTask","esri/tasks/FindParameters","esri/layers/ArcGISDynamicMapServiceLayer","esri/layers/ArcGISTiledMapServiceLayer",
	"esri/layers/FeatureLayer", "esri/tasks/query",
	"esri/tasks/QueryTask", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureMarkerSymbol",
	"esri/renderers/SimpleRenderer","esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol",
	"esri/Color", "esri/toolbars/draw","dijit/TooltipDialog", "dijit/popup",
	"esri/lang", "dojo/dom-style", "esri/graphic", "dojo/on", "dojo/number", "esri/geometry/Point", "esri/geometry/ScreenPoint",
	"dojo/parser", "esri/symbols/PictureMarkerSymbol", "esri/layers/GraphicsLayer", "esri/symbols/TextSymbol", "dijit/registry",
	 "dojo/domReady!"
], function(dom,       domConstruct,Map,Scalebar,Geoprocessor,InfoTemplate,FindTask,FindParameters,ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer,FeatureLayer, Query, QueryTask,
	SimpleMarkerSymbol, PictureMarkerSymbol, SimpleRenderer,SimpleFillSymbol, SimpleLineSymbol, Color, Draw,TooltipDialog, dijitPopup, esriLang, domStyle, Graphic, on,
	number, Point, ScreenPoint, parser, PictureMarkerSymbol, GraphicsLayer, TextSymbol, registry
) {
	map = new Map("mapDiv", {logo:false,
                 center:[118.85698,26.22509],
                 zoom:17,
                 slider:false
             });
            
           
             //闽清地图
             dojo.declare("MQTDTLayer", esri.layers.TiledMapServiceLayer, {
                 constructor: function () {
                     this.spatialReference = new esri.SpatialReference({ wkid: 4326 });
                     this.initialExtent = (this.fullExtent =
                     new esri.geometry.Extent(-180.0, -90.0, 180.0, 90.0, this.spatialReference));
                     this.tileInfo = new esri.layers.TileInfo({
                         "rows": 256,
                         "cols": 256,
                         "compressionQuality": 0,
                         "origin": { "x": -180, "y": 90 },
                         "spatialReference": { "wkid": 4326 },
                         "lods": [
                              /*{ "level": 0, "resolution": 0.703125, "scale": 295497593.05875 },
                              { "level": 1, "resolution": 0.3515625, "scale": 147748796.529375 },
                              { "level": 2, "resolution": 0.17578125, "scale": 73874398.264688 },
                              { "level": 3, "resolution": 0.087890625, "scale": 36937199.132344 },
                              { "level": 4, "resolution": 0.0439453125, "scale": 18468599.566172 },
                              { "level": 5, "resolution": 0.02197265625, "scale": 9234299.783086 },
                              { "level": 6, "resolution": 0.010986328125, "scale": 4617149.891543 },
                              { "level": 7, "resolution": 0.0054931640625, "scale": 2308574.945771 },*/
                              { "level": 8, "resolution": 0.00274658203125, "scale": 1154287.472886 },
                              { "level": 9, "resolution": 0.001373291015625, "scale": 577143.736443 },
                              { "level": 10, "resolution": 0.0006866455078125, "scale": 288571.86822143558 },
                              { "level": 11, "resolution": 0.00034332275390625, "scale": 144285.93411071779 },
                              { "level": 12, "resolution": 0.000171661376953125, "scale": 72142.967055358895 },
                              { "level": 13, "resolution": 8.58306884765625e-005, "scale": 36071.483527679447 },
                              { "level": 14, "resolution": 4.291534423828125e-005, "scale": 18035.741763839724 },
                              { "level": 15, "resolution": 2.1457672119140625e-005, "scale": 9017.8708819198619 },
                              { "level": 16, "resolution": 1.0728836059570313e-005, "scale": 4508.9354409599309 },
                              { "level": 17, "resolution": 5.3644180297851563e-006, "scale": 2254.4677204799655 },
                              { "level": 18, "resolution": 2.6822090148925781e-006, "scale": 1128.49943344138 },
                              { "level": 19, "resolution": 1.3411045074462891e-006, "scale": 564.2497166720689 },
                              ]
                     });
                     this.loaded = true;
                     this.onLoad(this);
                 },
                 getTileUrl: function (level, row, col) {

                return "http://120.40.102.247:9301/serviceaccess/WMTS/Image_CGCS2000?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=mq_img&STYLE=default&FORMAT=image/png&TILEMATRIXSET=mq_mq&TILEMATRIX="+(level+1)+"&TILEROW="+row+"&TILECOL="+col;
                 }
             });

             //福州地图
             dojo.declare("FZTDTLayer", MQTDTLayer, {
                 getTileUrl: function (level, row, col) {//wmts
                   
                 return "http://tdt.fuzhou.gov.cn/serviceaccess/wmts/Image2012CGCS2000?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=0&STYLE=default&FORMAT=image/png&TILEMATRIXSET=wmts&TILEMATRIX="+(level-8)+"&TILEROW="+row+"&TILECOL="+col;
                 }
             });
             fzLayer = new FZTDTLayer();
             map.addLayer(fzLayer);
             mqLayer = new MQTDTLayer();
             map.addLayer(mqLayer);
             extentLayer=new GraphicsLayer();
             map.addLayer(extentLayer);
             map.on("zoom-end",function(e){
             	console.log(e);
             	if(e.level<8){
             		mqLayer.hide();
             	}else{
             		mqLayer.show();
             	}
             })
             //地图默认定位
          
			//定位按钮
             $("#gpsBtn").click(function(){
		          if (navigator.geolocation)
				    {
				    	navigator.geolocation.getCurrentPosition(showPosition,showError);
				    	
				    }else{
				    	alert("浏览器不支持获取定位坐标！");
				    }
						    
             })
             
        function showPosition(position)
			  {
			  	console.log(position);
			  	var mapPoint=new Point(parseFloat(position.coords.longitude),parseFloat(position.coords.latitude),map.spatialReference);
			  	map.centerAndZoom(mapPoint, 17);
			  }
			  function showError(error)
			  {console.log(error)
			  switch(error.code)
			    {
			    case error.PERMISSION_DENIED:
			    alert("用户不允许获取坐标！");
			     
			      break;
			    case error.POSITION_UNAVAILABLE:
			      alert("坐标信息不可用！");
			      break;
			    case error.TIMEOUT:
			      alert("获取坐标超时！");
			      break;
			    case error.UNKNOWN_ERROR:
			      alert("发生未知错误！");
			      break;
			    }
			  }
			  //绘制
          $("#drawBtn").click(function(){
          	if(extentLayer){
          		extentLayer.clear();
          	}
          	initToolbar("POLYGON");
          })
          function initToolbar(geotype) {
			    	tb = new Draw(map);
			    	map.disableMapNavigation();
			    	if(geotype=="RECTANGLE"){
			    		tb.activate(Draw.RECTANGLE,{showTooltips:false});
			    	}else if(geotype=="POLYGON"){
			    		tb.activate(Draw.POLYGON,{showTooltips:false});
			    	}
			    	var lineSymbol = new SimpleLineSymbol(
						    SimpleLineSymbol.STYLE_DASH,new Color([255,255,0]),20);
					var fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
						    new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
						    new Color([255,0,0]), 20),new Color([255,255,0,0.25])
						  );   
			    	tb.setLineSymbol(lineSymbol);
			    	tb.setFillSymbol(fillSymbol)
			    	tb.on("draw-end", addGraphic);
			
			    }
           function addGraphic(evt) {
	           	console.log(evt);
	           	tb.deactivate();
				    	map.enableMapNavigation();
				    	var symbol;
				    	var lineSymbol = new SimpleLineSymbol(
						    SimpleLineSymbol.STYLE_DASH,new Color([255,0,0]),20);
						var fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
						    new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
						    new Color([255,0,0]), 20),new Color([255,255,0,0.25])
						  );   
				    	if(evt.geometry.type === "line" || evt.geometry.type === "polyline") {
				    		symbol = lineSymbol;
				    	} else {
				    		symbol = fillSymbol;
				    	}
				    	extentLayer.add(new Graphic(evt.geometry, symbol));
           }
           //清除绘制内容
           $("#drawClearBtn").click(function(){
			         
			        if(extentLayer){
	          		extentLayer.clear();
	          	}
			        tb.deactivate(); 
						    
          })
           //输出保存-可进一步添加写入mySql功能，需要保证在清除绘制图层内容之前完成保存
           $("#saveBtn").click(function(){
			var data=extentLayer.graphics[0].geometry.rings[0].length;
var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);//true
			         if(window.confirm('你确定要发送到多规合一吗？')){
                 //alert("确定");
				 //alert(extentLayer.graphics[0].geometry.rings[0].length);
                 return true;
              }else{
                 //alert("取消");
                 return false;
             }
			   				//alert(extentLayer.graphics[0].geometry.rings[0][2]);
				
          })
})